package net.zhnb.controller;

import java.math.BigDecimal;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.zhnb.bean.Ad;
import net.zhnb.bean.AdKey;
import net.zhnb.bean.Global;
import net.zhnb.bean.GlobalKey;
import net.zhnb.bean.Lottery;
import net.zhnb.bean.Shower;
import net.zhnb.bean.ShowerKey;
import net.zhnb.bean.Tag;
import net.zhnb.bean.TagKey;
import net.zhnb.service.AdService;
import net.zhnb.service.GlobalService;
import net.zhnb.service.LotteryService;
import net.zhnb.service.ShowerService;
import net.zhnb.service.TagService;
import net.zhnb.util.ProjectUtil;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import weibo4j.Friendships;
import weibo4j.Oauth;
import weibo4j.Timeline;
import weibo4j.Weibo;
import finaler.util.Page;
import finaler.util.PageList;

@Controller
@RequestMapping("main")
public class MainController {
	
	@Resource
	private TagService tagService;

	@Resource
	private GlobalService globalService;

	@Resource
	private LotteryService lotteryService;
	
	@Resource
	private ShowerService showerService;
	
	@Resource
	private AdService adService;
	
	//demo:http://localhost/main/tag_WkhOQl85NF9UQUc=
	@RequestMapping( value="/tag_{tag}" )
	public String tag(@PathVariable String tag,HttpServletRequest request) throws Exception {
		String defaultTag = ProjectUtil.decodeBase64(tag);
		String[] tagArray = defaultTag.split("_");
		if(tagArray.length<3){
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		if(ProjectUtil.isNum(tagArray[1])==false){
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		Tag tagDetail = tagService.findByKey(new TagKey(new BigDecimal(tagArray[1])));
		if (tagDetail==null) {
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		request.getSession().setAttribute("tagid", tagArray[1]);
		
		Shower shower = showerService.findShower(tagArray[1]);
		request.setAttribute("showerimg", shower.getShoweradimg() );
		request.getSession().setAttribute("showername", shower.getShowername());
		request.getSession().setAttribute("showerid", shower.getId());
		return "/main/welcome";
	}

	//demo:http://localhost/main/tag_WkhOQl85NF9UQUc=
	@RequestMapping( value="/ad_{ad}" )
	public String ad(@PathVariable String ad,HttpServletRequest request) throws Exception {
		String defaultAd = ProjectUtil.decodeBase64(ad);
		String[] adArray = defaultAd.split("_");
		if(adArray.length<3){
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		if(ProjectUtil.isNum(adArray[1])==false){
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		Ad adDetail = adService.findByKey(new AdKey(new BigDecimal(adArray[1])));
		if (adDetail==null) {
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		request.setAttribute("imgpath", adDetail.getImgpath());
		return "/main/ad";
	}

	@RequestMapping( value="/inputMobile" )
	public String inputMobile() throws Exception {
		return "/main/inputMobile";
	}
	
	@RequestMapping( value="/lottery" )
	public String lottery(HttpServletRequest request) throws Exception {
		//非法标签
		Tag tagDetail = tagService.findByKey(new TagKey(new BigDecimal(request.getParameter("tagid"))));
		if (tagDetail==null) {
			request.setAttribute("message", "标签错误,欢迎使用,再见!");
			return "/main/bye";
		}
		
		String mobile = request.getParameter("mobile");
		
		Global global = globalService.findByKey(new GlobalKey(new BigDecimal("1")));
		
		//抽奖超过次数
		int lotteryCount  = lotteryService.getLotteryCount(mobile);
		if(lotteryCount>=global.getLotterynum().intValue()){
			request.setAttribute("message", "你已抽奖"+global.getLotterynum()+"次,不能再抽奖了.抱歉!");
			return "/main/bye";
		}
		
		//跨轮抽奖
		int nowlun = tagDetail.getLotterylun().intValue();//此标签是第几轮
		/*
		if(nowlun>1){
			for(int i=1;i<nowlun;i++){
				if(lotteryService.getLotteryCount(mobile,i)==0){//如果统计数为0,证明此轮漏掉了
					request.setAttribute("message", "此标签是第"+nowlun+"轮抽奖,由于你没完成前面的第"+i+"轮次,所以不能参加此抽奖,再见!!");
					return "/main/bye";
				}
			}
		}*/
		
		//重复抽奖
		int existLottery = lotteryService.countByMobileShowerid(  mobile ,tagDetail.getLotterylun(),tagDetail.getShowerId() );
		if(existLottery>0){
			request.setAttribute("message", "此轮抽奖,你已经在此展位抽过了.不能重复抽,请去其它展位试试!");
			return "/main/bye";
		}
		
		Lottery lottery = new Lottery();
		lottery.setLun(tagDetail.getLotterylun());
		lottery.setMobile(mobile);
		lottery.setShowerid(tagDetail.getShowerId());
		lottery.setRoomid( showerService.findByKey( new ShowerKey( tagDetail.getShowerId() )).getRoomId() );
		lottery.setShareflag(new BigDecimal(0));
		lottery.setDatetime(ProjectUtil.getCurrentFormatStr("yyyy-MM-dd HH:mm:ss"));
		
		boolean hit  = false;
		if(nowlun==1){//第一轮用概率1
			hit  =  ProjectUtil.probabilityHit(global.getLotterypersent1().intValue());
		}else if(nowlun==2){//第二轮用概率2
			hit  =  ProjectUtil.probabilityHit(global.getLotterypersent2().intValue());
		}else if(nowlun==3){//第三轮用概率3
			hit  =  ProjectUtil.probabilityHit(global.getLotterypersent3().intValue());
		}
		
		Shower shower = showerService.findByKey(new ShowerKey( tagDetail.getShowerId()));
		request.setAttribute("shower", shower);
		
		if(!hit){
			lottery.setResult(new BigDecimal(0));
			lotteryService.insert(lottery);
			int lotteryId = lotteryService.getMaxLotteryId(mobile);
			request.getSession().setAttribute("lotteryId", lotteryId);
			return "/main/continue";
		}else{
			//恭喜你中奖了!!!
			lottery.setResult(new BigDecimal(1));
			lotteryService.insert(lottery);
			int lotteryId = lotteryService.getMaxLotteryId(mobile);
			request.getSession().setAttribute("lotteryId", lotteryId);
			return "/main/congratulate";
		}
	}

	@RequestMapping( value="/freeShare" )
	public String freeShare(HttpServletRequest request) throws Exception {
		if(request.getParameter("code")==null){
			Oauth oauth = new Oauth();
			return "redirect:"+oauth.authorize("code","","");
		}else{
			request.getSession().setAttribute("code",request.getParameter("code"));
			return "/main/freeShare";
		}
	}
	
	@RequestMapping( value="/share" )
	public String share(HttpServletRequest request) throws Exception {
		if(request.getParameter("code")==null){
			request.getSession().setAttribute("lotteryId",request.getParameter("lotteryId"));
			Oauth oauth = new Oauth();
			return "redirect:"+oauth.authorize("code","","");
		}else{
			request.getSession().setAttribute("code",request.getParameter("code"));
			return "/main/share";
		}
	}
	
	@RequestMapping( value="/shareSina" )
	public String shareSina(HttpServletRequest request) throws Exception {
		//分享
		boolean shareResult = false;
		
		Global global = globalService.findByKey(new GlobalKey(new BigDecimal("1")));
		
		Object lotteryId = request.getSession().getAttribute("lotteryId");
		String sinacontent = request.getParameter("sinacontent") + ProjectUtil.getCurrentFormatStr("\nyyyy-MM-dd HH:mm:ss");
		
		Oauth oauth = new Oauth();
		String access_token = oauth.getAccessTokenByCode(request.getSession().getAttribute("code").toString()).getAccessToken();
        Weibo weibo = new Weibo();
        weibo.setToken(access_token);

		//发微博
        Timeline tm = new Timeline();
        tm.client.setToken(access_token);
        try {
            tm.UpdateStatus(sinacontent);
            shareResult = true;
		} catch (Exception e) {
			shareResult = false;
		}
        
		//关注
		Friendships fm = new Friendships();
		fm.client.setToken(access_token);
		try {
			fm.createFriendshipsByName(global.getSystemweibo());
		} catch (Exception e) {
		}
		
		if(shareResult){
			if(lotteryId!=null&&!lotteryId.toString().equals("0")){
				Lottery lottery =  new Lottery();
				lottery.setId(new BigDecimal(lotteryId.toString()));
				lottery.setShareflag(new BigDecimal(1));
				lotteryService.update(lottery);
			}
			return "/main/shareOk";
		}else{
			request.setAttribute("message", "分享失败，可能信号不太给力哦!");
			return "/main/bye";
		}
	}
	
	@RequestMapping( value="/daoHang" )
	public String daoHang() throws Exception {
		return "/main/daoHang";
	}

	@RequestMapping( value="/query" )
	public String query(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(6);
		PageList lotteryList = lotteryService.getPageList(page);
		request.setAttribute("lotteryList", lotteryList);
		return "/main/query";
	}
}
